package org.jeecg.community.controller;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.jeecg.autopoi.poi.excel.def.NormalExcelConstants;
import org.jeecg.autopoi.poi.excel.entity.ExportParams;
import org.jeecg.autopoi.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionColumn;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.community.entity.XyParkBill;
import org.jeecg.community.entity.XyParkBillHouse;
import org.jeecg.community.entity.XyParkContract;
import org.jeecg.community.entity.XyParkContractFee;
import org.jeecg.community.entity.XyParkContractHouse;
import org.jeecg.community.service.IXyParkBillHouseService;
import org.jeecg.community.service.IXyParkBillService;
import org.jeecg.community.service.IXyParkContractFeeService;
import org.jeecg.community.service.IXyParkContractHouseService;
import org.jeecg.community.service.IXyParkContractService;
import org.jeecg.modules.system.service.SnRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 园区物业-合同管理
 * @author: MxpIO
 */
@Api(tags = "园区物业-合同管理")
@RestController
@RequestMapping("/community/contract")
public class XyParkContractController {
	
	@Autowired
	private IXyParkContractService xyParkContractService;
	
	@Autowired
	private IXyParkContractFeeService xyParkContractFeeService;
	
	@Autowired
	private IXyParkContractHouseService xyParkContractHouseService;
	
	@Autowired
	private SnRuleService snRuleService;
	
	@Autowired
	private IXyParkBillService xyParkBillService;
	
	@Autowired
	private IXyParkBillHouseService xyParkBillHouseService;
	
	/**
	 * 合同管理-分页列表查询
	 * @param xyParkContract
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "合同管理-分页列表查询")
	@ApiOperation(value = "合同管理-分页列表查询", notes = "合同管理-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(XyParkContract xyParkContract,
			@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
			@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
		QueryWrapper<XyParkContract> queryWrapper = QueryGenerator.initQueryWrapper(xyParkContract,
				req.getParameterMap());
		Page<XyParkContract> page = new Page<XyParkContract>(pageNo, pageSize);
		IPage<XyParkContract> pageList = xyParkContractService.page(page, queryWrapper);
		xyParkContractService.handleDetails(pageList);
		return Result.OK(pageList);
	}
	
	/**
	 * 添加
	 * 
	 * @param xyParkContract
	 * @return
	 */
	@AutoLog(value = "合同管理-添加")
	@ApiOperation(value = "合同管理-添加", notes = "合同管理-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody XyParkContract xyParkContract) {
		List<XyParkContractFee> fees = xyParkContract.getXyParkContractFees();
		if(fees != null){
			for(XyParkContractFee fee : fees){
				fee.setContractCode(xyParkContract.getContractCode());
				xyParkContractFeeService.save(fee);
			}
		}
		
		
		List<XyParkContractHouse> houses = xyParkContract.getXyParkContractHouses();
		if(houses != null){
			for(XyParkContractHouse house : houses){
				house.setContractCode(xyParkContract.getContractCode());
				xyParkContractHouseService.save(house);
			}
		}
		
		xyParkContractService.save(xyParkContract);
		return Result.OK("添加成功！", xyParkContract);
	}

	/**
	 * 编辑
	 * 
	 * @param xyParkContract
	 * @return
	 */
	@AutoLog(value = "合同管理-编辑")
	@ApiOperation(value = "合同管理-编辑", notes = "合同管理-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody XyParkContract xyParkContract) {
		xyParkContractFeeService.remove(new QueryWrapper<XyParkContractFee>().eq("contract_code", xyParkContract.getContractCode()));
		xyParkContractHouseService.remove(new QueryWrapper<XyParkContractHouse>().eq("contract_code", xyParkContract.getContractCode()));
		
		List<XyParkContractFee> fees = xyParkContract.getXyParkContractFees();
		if(fees != null){
			for(XyParkContractFee fee : fees){
				fee.setContractCode(xyParkContract.getContractCode());
				xyParkContractFeeService.save(fee);
			}
		}
		
		
		List<XyParkContractHouse> houses = xyParkContract.getXyParkContractHouses();
		if(houses != null){
			for(XyParkContractHouse house : houses){
				house.setContractCode(xyParkContract.getContractCode());
				xyParkContractHouseService.save(house);
			}
		}
		xyParkContractService.updateById(xyParkContract);
		return Result.OK("编辑成功!", xyParkContract);
	}
	
	/**
	 * 通过id删除
	 * 
	 * @param id
	 * @return
	 */
	@AutoLog(value = "合同管理-通过id删除")
	@ApiOperation(value = "合同管理-通过id删除", notes = "合同管理-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
		XyParkContract xyParkContract = xyParkContractService.getById(id);
		xyParkContractFeeService.remove(new QueryWrapper<XyParkContractFee>().eq("contract_code", xyParkContract.getContractCode()));
		xyParkContractHouseService.remove(new QueryWrapper<XyParkContractHouse>().eq("contract_code", xyParkContract.getContractCode()));
		xyParkContractService.removeById(id);
		return Result.OK("删除成功!", id);
	}

	/**
	 * 批量审批
	 * 
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "合同管理-批量审批")
	@ApiOperation(value = "合同管理-批量审批", notes = "合同管理-批量审批")
	@GetMapping(value = "/approvalBatch")
	public Result<?> approvalBatch(@RequestParam(name = "ids", required = true) String ids,
			@RequestParam(name = "status", required = true) String status) {
		List<String> idList = Arrays.asList(ids.split(","));
		xyParkContractService.approvalByIds(idList,status);
		return Result.OK("批量审批成功!", null);
	}
	
	@AutoLog(value = "合同管理-账单生成")
	@ApiOperation(value = "合同管理-账单生成", notes = "合同管理-账单生成")
	@GetMapping(value = "/generateBill")
	public Result<?> generateBill(@RequestParam(name = "contractCode", required = true) String contractCode){
		XyParkContract contract = xyParkContractService.getOne(new QueryWrapper<XyParkContract>().eq("contract_code", contractCode));
		List<XyParkContractFee> fees = xyParkContractFeeService.list(new QueryWrapper<XyParkContractFee>().eq("contract_code", contractCode));
		List<XyParkContractHouse> houses = xyParkContractHouseService.list(new QueryWrapper<XyParkContractHouse>().eq("contract_code", contractCode));
		int count = xyParkBillService.count(new QueryWrapper<XyParkBill>().eq("contract_code", contractCode));
		
		if(fees != null && count == 0){
			for(XyParkContractFee fee : fees){
				XyParkBill bill = new XyParkBill();
				bill.setAmount(fee.getPrice());
				bill.setDueDate(fee.getCollectionDate());
				bill.setStartDate(fee.getStartDate());
				bill.setEndDate(fee.getEndDate());
				bill.setBillStatus("3");
				bill.setContractCode(contractCode);
				bill.setBillSource("2");
				bill.setCostType(fee.getCostType());
				bill.setOwnerCode(contract.getOwnerCode());
				bill.setCustomerAccount(contract.getAccount());
				bill.setBillCode(snRuleService.execute("XY-sk-${YYYY}-###", null) + "");
				bill.setBillType("1");
				xyParkBillService.save(bill);
				if(houses != null){
					for(XyParkContractHouse house : houses){
						XyParkBillHouse billHouse = new XyParkBillHouse();
						billHouse.setBillCode(bill.getBillCode());
						billHouse.setBuildingArea(house.getBuildingArea());
						billHouse.setBuildingName(house.getBuildingName());
						billHouse.setFloor(house.getFloor());
						billHouse.setHouseCode(house.getHouseCode());
						billHouse.setProjectName(house.getProjectName());
						billHouse.setPropertyArea(house.getPropertyArea());
						xyParkBillHouseService.save(billHouse);
					}
				}
			}
		}else if(count > 0){
			return Result.error("合同已存在账单！");
		}else{
			return Result.error("合同无账单可生成！");
		}
		return Result.OK("账单生成成功!", null);
	}
	
	/**
	 * 批量删除
	 * 
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "合同管理-批量删除")
	@ApiOperation(value = "合同管理-批量删除", notes = "合同管理-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
		List<String> idList = Arrays.asList(ids.split(","));
		for(String id : idList){
			XyParkContract xyParkContract = xyParkContractService.getById(id);
			xyParkContractFeeService.remove(new QueryWrapper<XyParkContractFee>().eq("contract_code", xyParkContract.getContractCode()));
			xyParkContractHouseService.remove(new QueryWrapper<XyParkContractHouse>().eq("contract_code", xyParkContract.getContractCode()));
		}
		xyParkContractService.removeByIds(idList);
		return Result.OK("批量删除成功!", null);
	}
	
	/**
	 * 导出
	 * 
	 * @return
	 */
	@RequestMapping(value = "/export")
	public ModelAndView export(HttpServletRequest request,
			XyParkContract xyParkContract) {
		// Step.1 组装查询条件
		QueryWrapper<XyParkContract> queryWrapper = QueryGenerator.initQueryWrapper(xyParkContract,
				request.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		// Step.2 获取导出数据
		List<XyParkContract> pageList = xyParkContractService.list(queryWrapper);
		List<XyParkContract> exportList = null;

		// 过滤选中数据
		String selections = request.getParameter("selections");
		if (oConvertUtils.isNotEmpty(selections)) {
			List<String> selectionList = Arrays.asList(selections.split(","));
			exportList = pageList.stream().filter(item -> selectionList.contains(item.getId()))
					.collect(Collectors.toList());
		} else {
			exportList = pageList;
		}

		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "合同管理"); // 此处设置的filename无效
																// ,前端会重更新设置一下
		mv.addObject(NormalExcelConstants.CLASS, XyParkContract.class);
		mv.addObject(NormalExcelConstants.PARAMS,
				new ExportParams("合同管理", "导出人:" + sysUser.getRealname(), "合同管理"));
		mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		return mv;
	}
}
